package com.example.lanouhn.firstapp.activity.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.example.lanouhn.firstapp.R;
import com.example.lanouhn.firstapp.activity.adapter.GoodsListAdapter;
import com.example.lanouhn.firstapp.activity.constants.Constants;
import com.example.lanouhn.firstapp.activity.model.GoodsList;
import com.example.lanouhn.firstapp.activity.utils.GoodsListJson;
import com.example.lanouhn.firstapp.activity.utils.HttpUtils;
import com.example.lanouhn.firstapp.activity.view.xlistview.XListView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 首页搜索跳转商品列表界面
 */
public class GoodsListActivity extends AppCompatActivity {

    //获取请求网址
    private String getRequestUrl() {
        return Constants.GOODS_LIST_URL + "&key=" + key + "&order=" + order + "&page=" + pageSize + "&curpage=" + currentPage;
    }

    //定义变量
    private XListView listView;
    private RadioGroup radioGroup;
    //一个中间量集合
    private List<GoodsList> tempList;
    //定义商品id
    private String goods_id;
    //排序类型
    private int key = 4;//4代表新品，3代表价格 2代表销量 1代表人气
    //当前页
    private int currentPage = 1;
    private int pageSize = 10;
    //升降序标识
    private boolean orderFlag = true;
    private int order = 1;//升序1，降序2

    private boolean isFirstRequest = true;


    private List<GoodsList> list;
    private GoodsListAdapter adapter;
    //加载进度
    private ProgressBar progressBar;


    //返回
    private ImageView iv_back;
    //弹出标题栏
    private LinearLayout ll_title;
    private ImageView iv_goodsList;
    private boolean isImageView = true;


    //隐藏标题栏跳转
    private RelativeLayout rl_homePage;
    private RelativeLayout rl_classify;
    private RelativeLayout rl_shoppingCart;
    private RelativeLayout rl_myStore;

    private Handler handler = new Handler() {


        @Override
        public void handleMessage(Message msg) {

            //取消进度
            progressBar.setVisibility(View.GONE);
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    Toast.makeText(GoodsListActivity.this,
                            "网络链接失败，请稍后再试", Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    adapter = new GoodsListAdapter(GoodsListActivity.this, list);
                    listView.setAdapter(adapter);

                    listView.stopRefresh();
                    listView.setPullLoadEnable(true);
                    adapter.notifyDataSetChanged();

                    break;
                case 2://加载更多数据
                    list.addAll(tempList);
                    //刷新页面
                    adapter.notifyDataSetChanged();
                    //清空中间集合量
                    tempList.removeAll(tempList);
                    //停止加载listView
                    listView.stopLoadMore();

                    break;

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_list);

        //找到控件
        initView();
        //获取网络请求数据
        getDataFromWeb();
        //监听事件
        initEvent();
    }

    private void initView() {

        rl_homePage = (RelativeLayout) findViewById(R.id.rl_homePage);
        rl_classify = (RelativeLayout) findViewById(R.id.rl_classify);
        rl_shoppingCart = (RelativeLayout) findViewById(R.id.rl_shoppingCart);
        rl_myStore = (RelativeLayout) findViewById(R.id.rl_myStore);
        listView = (XListView) findViewById(R.id.listView);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
        //开启加载更多功能 设置上拉加载的开关
        listView.setPullLoadEnable(true);

        ll_title = (LinearLayout) findViewById(R.id.ll_title);
        iv_goodsList = (ImageView) findViewById(R.id.goodsList);

        //返回
        iv_back = (ImageView) findViewById(R.id.iv_back);


    }


    //radioButton点击选中事件
    private void initEvent() {
        //设置默认的RadioButton
        radioGroup.check(R.id.rb_newProduct);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i) {
                    case R.id.rb_newProduct://新品
                        key = 4;
                        break;
                    case R.id.rb_price://价格
                        key = 3;
                        if (orderFlag)
                            order = 1;
                        else
                            order = 2;

                        orderFlag = !orderFlag;
                        break;
                    case R.id.rb_sales://销量
                        key = 2;
                        break;
                    case R.id.rb_popularity://人气
                        key = 1;
                        break;

                }
                //重新获取数据并填充listView
                getDataFromWeb();

            }
        });
        //listView的刷新加载监听事件

        listView.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                //下拉刷新
                currentPage++;
                getDataFromWeb();

            }

            @Override
            public void onLoadMore() {
                //上拉更多
                currentPage ++;
                getMoreDataFromWeb();

            }
        });

        //listView的监听事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(GoodsListActivity.this,GoodsDetailsActivity.class);
                intent.putExtra("goods_id",list.get(i-1).getGoods_id());
                startActivity(intent);
            }
        });


        //返回按钮监听事件
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent it = new Intent();
                setResult(101,it);
                finish();
            }
        });


        //弹出标题栏监听事件
        iv_goodsList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isImageView) {
                    ll_title.setVisibility(View.VISIBLE);
                    isImageView = false;
                } else {
                    ll_title.setVisibility(View.GONE);
                    isImageView = true;

                }
            }
        });

        //标题栏首页按钮监听事件
        rl_homePage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(GoodsListActivity.this,MainActivity.class);
                intent.putExtra("symbol",1);
                startActivity(intent);
            }
        });
        //标题栏分类按钮监听事件
        rl_classify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(GoodsListActivity.this,MainActivity.class);
                intent.putExtra("symbol",2);
                startActivity(intent);
            }
        });
        //标题栏购物车按钮监听事件
        rl_shoppingCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(GoodsListActivity.this,MainActivity.class);
                intent.putExtra("symbol",3);
                startActivity(intent);
            }
        });
        //标题栏我的商城按钮监听事件
        rl_myStore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(GoodsListActivity.this,MainActivity.class);
                intent.putExtra("symbol",4);
                startActivity(intent);
            }
        });
    }

    private void getMoreDataFromWeb() {
        tempList = new ArrayList<>();

        new Thread(new Runnable() {
            @Override
            public void run() {
                //使用OKHttp 获取解析数据
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(getRequestUrl())
                        .build();

                Call call = client.newCall(request);

                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        handler.sendEmptyMessage(0);
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        tempList = GoodsListJson.getGoodsList(response.body().string());
                        if (tempList.size() > 0) {
                            handler.sendEmptyMessage(2);
                        }
                    }
                });

            }


        }).start();

    }


    //获取数据
    private void getDataFromWeb() {
        //显示加载进度条
        if (isFirstRequest) {
            //加载进度
            progressBar.setVisibility(View.VISIBLE);
        }
        //开启线程

        new Thread(new Runnable() {
            @Override
            public void run() {
                //调用HttpUtils类，来请求网络获取Json数据
                String result = HttpUtils.doGet(getRequestUrl());
                //判断是否获取到Json数据
                if (!result.equals("") && !result.equals("null")) {

                    //将获取到的json数据解析，通过封装的工具类
                    list = GoodsListJson.getGoodsList(result);

                    //判断解析出的集合的长度，有数据就显示，无数据就不显示
                    if (list.size() > 0) {
                        //获取数据成功
                        handler.sendEmptyMessage(1);
                    } else {
                        handler.sendEmptyMessage(0);
                    }
                } else {
                    //获取Json数据失败
                    handler.sendEmptyMessage(0);
                }


            }
        }).start();

        //第一次显示，第二次下拉刷新不显示
        isFirstRequest = false;
    }


}